package com.xiayuanxing.arithmetic.DataStructures.Tree;

/**
 * @program: arithmetic
 * @description: 顺序二叉树
 * @author: xia yuan xing
 * @create: 2021-10-07 10:05
 */
public class ArrayBinaryTreeDemo {

    public static void main(String[] args) {

        int[] array = {1,2,3,4,5,6,7};


        //测试
        ArrayBinaryTree arrayBinaryTree = new ArrayBinaryTree(array);
        arrayBinaryTree.preOrder();

    }
}


class ArrayBinaryTree{

    //存储数据节点的数组
    private int[] array;

    //构造器
    public ArrayBinaryTree(int[] array) {
        this.array = array;
    }

    /**
     * 重载preOrder
     */
    public void preOrder(){
        this.preOrder(0);
    }

    /**
     * 顺序存储前序二叉树遍历
     * @param index
     */
    public void preOrder(int index){
        //校验数组
        if (array == null || array.length == 0){
            System.out.println("数组为空，不能按照二叉树的前序遍历");
        }

        //输出当前元素
        System.out.print(" "+array[index]);

        //向左递归遍历
        if ((index * 2 + 1) < array.length){
            preOrder(2 * index + 1);
        }

        //向右递归遍历
        if ((index * 2 + 2) < array.length){
            preOrder(2 * index + 2);
        }
    }
}